package com.demo.crm.springboot3security.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 自定义安全过滤器
 * 使用新的授权管理器API实现请求过滤
 */
@Component
@RequiredArgsConstructor
public class CustomFilterSecurityInterceptor extends OncePerRequestFilter {

    private final CustomAccessDecisionManager accessDecisionManager;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        // 如果是公开资源，直接放行
        if (isPublicResource(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }

        // 创建请求上下文
        RequestAuthorizationContext context = new RequestAuthorizationContext(request);

        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 检查授权
        AuthorizationDecision decision = accessDecisionManager.check(
                () -> authentication,
                context
        );

        if (decision != null && decision.isGranted()) {
            filterChain.doFilter(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "权限不足");
        }
    }

    private boolean isPublicResource(String url) {
        return url.startsWith("/api/auth/") || 
               url.equals("/error") || 
               url.equals("/test");
    }
} 